<template>
  <div class="dataTable">
    <div class="search_area">
      <el-form ref="searchForm" :inline="true" :model="searchForm">
        <el-form-item prop="keyword">
          <el-input v-model="searchForm.keyword" style="width: 260px" placeholder="输入资料名称查询" @keyup.enter.native="onSearch" />
        </el-form-item>
        <el-form-item prop="filter_time">
          <el-date-picker
            v-model="searchForm.filter_time"
            type="daterange"
            align="right"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-button style="margin-left:50px;" type="primary" :loading="loading" @click="onSearch">查询</el-button>
        <el-button style="margin-left:30px;" plain :loading="loading" @click="resetForm('searchForm')">重置</el-button>
        <el-button style="float: right;width: 125px;" type="primary" :loading="loading" @click="toUploadFile">
          <div class="upload_btn_icon" />上传资料
        </el-button>
        <el-form-item style="margin-left:50px;">

        <!-- <el-button style="float: right;width: 120px;" :loading="loading || exporting" type="primary" @click="exportData">导出</el-button> -->
        </el-form-item>
      </el-form>
    </div>
    <div class="table_area">
      <el-table
        v-loading="loading"
        :data="dataList"
        style="width: 100%"
        @selection-change="selectionChange"
      >
        <el-table-column
          type="selection"
          width="50"
        />
        <el-table-column
          prop="filename"
          label="文档"
          width="350"
        >
          <div slot-scope="{row}" class="flex">
            <div class="textOverflow">{{ row.filename }}</div>
            <div class="edit_filename_icon" @click="editFileName(row)" />
          </div>
        </el-table-column>
        <el-table-column
          prop="filesize"
          label="大小"
          width="200"
        >
          <div slot-scope="{row}">
            {{ formatFileSize(row.filesize) }}
          </div>
        </el-table-column>
        <el-table-column
          prop="group.name"
          label="分组"
          width="300"
        />
        <el-table-column
          prop="create_time"
          label="上传时间"
          width="300"
        />
        <el-table-column
          prop="operate"
          label="操作"
          width="280"
        >
          <div slot-scope="{row}" style="display: flex;">
            <el-tooltip effect="dark" content="下载" placement="top">
              <div class="download_icon" @click="download(row)" />
            </el-tooltip>
            <el-tooltip effect="dark" content="查看" placement="top">
              <div class="check_icon" @click="checkFile(row)" />
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top">
              <div class="delete_icon" @click="remove(row)" />
            </el-tooltip>
          </div>
        </el-table-column>
      </el-table>
      <div class="pager_area flex">
        <div class="flex">
          <div class="checked_tips">已选 {{ selectionedList.length }} 条 </div>
          <div class="batch_btn" @click="batchDownload()">
            <div class="batch_download" />
            <div class="text">批量下载</div>
          </div>
          <div class="batch_btn" @click="remove()">
            <div class="batch_delete" />
            <div class="text">批量删除</div>
          </div>
        </div>
        <el-pagination
          :current-page="pager.page"
          :page-sizes="pager.pageSizes"
          :page-size="pager.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pager.total"
          @size-change="pageSizeChange"
          @current-change="pageChange"
        />
      </div>
    </div>
    <EditFileName ref="EditFileName" :visible="editfileName_visible" :check-data="checkData" @close="editfileName_close" />
    <UploadFile :visible="uploadFile_visible" :group-id="groupId" :file-type="fileType" @close="closeUploadFile" />
    <CheckFile :visible="checkFile_visible" :file-url="fileUrl" @close="closeCheckFile" />
  </div>
</template>
<script>
import JSZip from 'jszip'
import axios from 'axios'
import { saveAs } from 'file-saver'
import { material_list, material_delete } from '@/api/material'
import EditFileName from './editFileName-dialog.vue'
import UploadFile from './uploadFile.vue'
import CheckFile from './checkFile.vue'

const getFile = (url) => {
  return new Promise((resolve, reject) => {
    axios(url, {
      method: 'GET',
      responseType: 'blob'
    }).then((res) => {
      resolve(res)
    }).catch((error) => {
      reject(error)
    })
  })
}

const compressAndDownload = (data, fileName) => {
  const zip = new JSZip()
  const promises = [] // 用于存储多个promise
  data.forEach((item) => {
    const promise = getFile(item.url).then((res) => {
      const fileName = item.filename
      zip.file(fileName, res, { binary: true })
    })
    promises.push(promise)
  })

  Promise.all(promises).then(() => {
    zip.generateAsync({
      type: 'blob',
      compression: 'DEFLATE', // STORE：默认不压缩 DEFLATE：需要压缩
      compressionOptions: {
        level: 9 // 压缩等级1~9    1压缩速度最快，9最优压缩方式
      }
    }).then((res) => {
      saveAs(res, fileName || '压缩包.zip') // 利用file-saver保存文件
    })
  })
}

export default {
  name: 'DataTable',
  components: { EditFileName, UploadFile, CheckFile },
  props: {
    groupId: {
      type: Number,
      default: 0
    },
    fileType: {
      type: Number,
      default: 1
    }
  },
  data() {
    // 这里存放数据
    return {
      loading: false,
      exporting: false,
      dataList: [],
      searchForm: {
        keyword: '',
        filter_time: ''
      },
      pager: {
        page: 1,
        pageSizes: [5, 10, 20],
        pageSize: 10,
        total: 0
      },
      detail_visible: false,
      checkData: {},
      loadParams: {},
      selectionedList: [],
      editfileName_visible: false,
      uploadFile_visible: false,
      checkFile_visible: false,
      fileUrl: ''
    }
  },
  computed: {

  },
  // 监控data中的数据变化
  watch: {
    groupId(n, o) {
      this.loadData()
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  async created() { },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  // 生命周期 - keep-alive
  async activated() { },
  // 方法集合
  methods: {
    async loadData() {
      this.loading = true
      try {
        const param = {
          page: this.pager.page,
          per_page: this.pager.pageSize,
          with: 'group',
          group: this.groupId || undefined,
          filetype: this.fileType,
          start_time: this.searchForm.filter_time ? this.searchForm.filter_time[0] : undefined,
          end_time: this.searchForm.filter_time ? this.searchForm.filter_time[1] : undefined,
          keyword: this.searchForm.keyword
        }
        const { code, data } = await material_list(param)
        if (!code) {
          this.dataList = data.data
          const { pager } = this
          pager.page = data.current_page
          pager.total = data.total
          pager.pageSize = Number(data.per_page)
        }
        this.loading = false
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    remove(data) {
      let tips = ''
      if (data) {
        tips = `确认删除资料 ${data.filename}？`
      } else {
        if (!this.selectionedList.length) return this.$messageOnce.warning('请选择要删除的数据')
        tips = '确认删除所选资料？'
      }
      this.$confirm(tips, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.loading = true
        try {
          const pathParam = data ? data.id : this.getAttributes('id', this.selectionedList).join(',')
          const { code, message } = await material_delete(pathParam)
          if (!code) {
            this.$messageOnce.success(message)
            this.onSearch()
          }
          this.loading = false
        } catch (error) {
          console.error(error)
        } finally {
          this.loading = false
        }
      }).catch(() => { })
    },
    batchDownload() {
      const { selectionedList } = this
      if (!selectionedList.length) {
        this.$messageOnce.warning('请选择要下载的文件')
      }
      selectionedList.forEach(e => {
        this.downloadFile(e.url)
      })
    },
    downloadFile(url) { // 下载文件方法
      const iframe = document.createElement('iframe')
      iframe.style.display = 'none' // 防止影响页面
      iframe.style.height = 0 // 防止影响页面
      iframe.src = url
      document.body.appendChild(iframe) // 这一行必须，iframe挂在到dom树上才会发请求
      setTimeout(() => {
        iframe.remove()
      }, 5 * 60 * 1000)
    },
    download(data) {
      // saveAs(data.url, 'data.filename')
      const a = document.createElement('a')
      a.setAttribute('href', data.url)
      a.setAttribute('download', data.filename)
      a.click()
      a.remove()
    },
    downloada(url) {
      const name = 'test'
      const image = new Image()
      image.setAttribute('crossOrigin', 'anonymous')
      image.src = url.url
      image.onload = () => {
        const canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        const ctx = canvas.getContext('2d')
        ctx.drawImage(image, 0, 0, image.width, image.height)
        canvas.toBlob((blob) => {
          const url = URL.createObjectURL(blob)
          this.downloadb(url, name)

          URL.revokeObjectURL(url)
        })
      }
    },
    downloadb(href, name) {
      const eleLink = document.createElement('a')
      eleLink.download = name
      eleLink.href = href
      eleLink.click()
      eleLink.remove()
    },
    formatFileSize(value) {
      if (value == null || value === '') {
        return '0 Bytes'
      }
      var unitArr = [' Bytes', ' Kb', ' Mb', ' Gb', ' Tb', ' Pb', ' Eb', ' Zb', ' Yb']
      var index = 0
      var srcsize = parseFloat(value)
      index = Math.floor(Math.log(srcsize) / Math.log(1024))
      var size = srcsize / Math.pow(1024, index)
      size = size.toFixed(2)// 保留的小数位数
      return size + unitArr[index]
    },
    getAttributes(attributes, dataList) {
      if (!attributes && !dataList.lenght) {
        return
      }
      const arr = []
      for (let i = 0; i < dataList.length; i++) {
        arr.push(dataList[i][attributes])
      }
      return arr
    },
    checkFile(row) {
      this.fileUrl = row.url
      this.checkFile_visible = true
    },
    closeCheckFile() {
      this.checkFile_visible = false
    },
    toUploadFile() {
      this.uploadFile_visible = true
    },
    closeUploadFile() {
      this.uploadFile_visible = false
    },
    onSearch() {
      const { pager } = this
      pager.page = 1
      this.loadData()
      this.$emit('reloadGroupList')
    },
    selectionChange(val) {
      this.selectionedList = val
    },
    editFileName(data) {
      this.editfileName_visible = true
      this.checkData = data
    },
    editfileName_close() {
      this.editfileName_visible = false
    },
    pageSizeChange(val) {
      const { pager } = this
      pager.pageSize = val
      this.loadData()
    },
    pageChange(val) {
      const { pager } = this
      pager.page = val
      this.loadData()
    },
    resetForm() {
      this.$refs.searchForm.resetFields()
      this.loadData()
    }
  },
  // 进入页面前
  beforeRouteEnter(to, from, next) {
    next(vm => {

    })
  },
  // 离开页面前
  beforeRouteLeave(to, from, next) {
    next()
  }
}
</script>
<style lang="scss" scoped>
 @import "~@/styles/mixin.scss";

.dataTable{
	width: 1540px;
	background-color: #FFFFFF;
	border-radius: 8px;
	.search_area{
		padding: 40px 30px 0 30px;
		border-bottom: 1px solid #E4E4E4;
	}
	.table_area{
		padding: 30px;
	}
}

.pager_area {
	margin-top: 40px;
}

.checked_tips{
	height: 28px;
	font-size: 14px;
	font-family: SourceHanSansCN-Medium, SourceHanSansCN;
	font-weight: 500;
	color: #606266;
	line-height: 28px;
	margin-right: 20px;
}

.batch_btn {
	width: 100px;
	height: 28px;
	background: #F7F7F7;
	border-radius: 4px;
	border: 1px solid #2C2C2C;
	display: flex;
	padding: 5px 8px;
	margin-right: 20px;
	color: #2C2C2C;
	cursor: pointer;
	.text{
		height: 14px;
		font-size: 14px;
		font-family: SourceHanSansCN-Regular, SourceHanSansCN;
		font-weight: 400;
		margin-left: 7px;
	}
	&:hover{
		width: 100px;
		height: 28px;
		border-radius: 4px;
		background: #FFFFFF;
		border: 1px solid $MainColor;
		display: flex;
		padding: 5px 8px;
		margin-right: 20px;
		color: $MainColor;
		cursor: pointer;
		.batch_delete {
			width: 16px;
			height: 15px;
			background: url('../../assets/material/batch_delete_active.png');
			background-size: 100%;
		}
		.batch_download {
			width: 16px;
			height: 17px;
			background: url('../../assets/material/batch_download_active.png');
			background-size: 100%;
		}
	}
}

.batch_delete {
	width: 16px;
	height: 15px;
	background: url('../../assets/material/batch_delete.png');
	background-size: 100%;
}

.batch_download {
	width: 16px;
	height: 17px;
	background: url('../../assets/material/batch_download.png');
	background-size: 100%;
}

.download_icon {
	background: url('../../assets/download@list.png');
  @include list_icons;
	margin-right: 30px;
  width: 30px;
  height: 31px;
}

.check_icon {
	background: url('../../assets/check@list.png');
  @include list_icons;
	margin-right: 30px;
  width: 33px;
}

.delete_icon {
background: url('../../assets/delete@list.png');
  @include list_icons;
}

.upload_btn_icon {
	width: 16px;
	height: 14px;
	background: url('../../assets/material/upload_btn_icon.png');
	background-size: 100%;
	margin-bottom: -2px;
	margin-right: 12px;
	display: inline-block;
}

.edit_filename_icon {
	width: 16px;
	height: 16px;
	background: url('../../assets/material/edit_filename.png');
	background-size: 100%;
	cursor: pointer;
	margin-right: 30px;
}

.edit_filename_icon:hover {
	width: 16px;
	height: 16px;
	background: url('../../assets/material/edit_filename_active.png');
	background-size: 100%;
	cursor: pointer;
	margin-right: 30px;
}

.flex{
	display: flex;
	align-content: center;
	justify-content: space-between;
}

.textOverflow {
  width: 280px;
  overflow:hidden;
  text-overflow:ellipsis;
  white-space:nowrap;
}

::v-deep .el-date-editor--daterange.el-input__inner {
    width: 260px;
}

::v-deep .el-select {
    display: inline-block;
    position: relative;
    width: 100%;
}
</style>
